package com.caocaog.market.controller;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.caocaog.market.entity.ShopBasic;
import com.caocaog.market.entity.ShopTakeoutHis;
import com.caocaog.market.service.IShopBasicService;
import com.caocaog.market.service.IShopTakeoutHisService;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import com.caocaog.market.entity.ShopTakeout;
import com.caocaog.market.service.IShopTakeoutService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * 店铺外卖信息
 *
 * @author guofeiyan
 * @date 2021-11-22
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(value = "shopTakeout", tags = "店铺外卖信息")
@RequestMapping("/shop/shopTakeout")
public class ShopTakeoutController extends JeecgController<ShopTakeout, IShopTakeoutService> {
    @Autowired
    private IShopTakeoutService shopTakeoutService;
    @Autowired
    private IShopBasicService shopBasicService;
    @Autowired
    private CommonAPI commonAPI;
    @Autowired
    private IShopTakeoutHisService shopTakeoutHisService;

    /**
     * 分页列表查询
     *
     * @param shopTakeout
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "店铺外卖信息-分页列表查询")
    @ApiOperation(value = "店铺外卖信息-分页列表查询", notes = "店铺外卖信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ShopTakeout shopTakeout,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<ShopTakeout> queryWrapper = QueryGenerator.initQueryWrapper(shopTakeout, req.getParameterMap());
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isNotEmpty(loginUser.getUserType()) && 1 != loginUser.getUserType()) {
            LambdaQueryWrapper<ShopBasic> shopQuery = new LambdaQueryWrapper<>();
            if (2 == loginUser.getUserType()) {

                //分站
                String siteId = loginUser.getSiteId();
                //获取商户ids
                List<String> merchantIds = commonAPI.findMerchantForSite(siteId);
                //获取门店
                if (oConvertUtils.listIsNotEmpty(merchantIds)) {

                    shopQuery.in(ShopBasic::getMerchantId, merchantIds);
                    List<String> shopIds = shopBasicService.list(shopQuery).stream().map(ShopBasic::getId).collect(Collectors.toList());
                    if (oConvertUtils.listIsNotEmpty(shopIds)) {
                        queryWrapper.in("shop_id", shopIds);
                    }

                }

            } else if (3 == loginUser.getUserType()) {
                //商户
                String merchantId = loginUser.getMerchantId();
                //获取门店
                // 首先获取选择的门店
//                if (oConvertUtils.isNotEmpty(loginUser.getCurrentSelectedShopId())) {
//                    queryWrapper.in("shop_id", loginUser.getCurrentSelectedShopId());
//                } else {
                    shopQuery.eq(ShopBasic::getMerchantId, merchantId);
                    List<String> shopIds = shopBasicService.list(shopQuery).stream().map(ShopBasic::getId).collect(Collectors.toList());
                    if (oConvertUtils.listIsNotEmpty(shopIds)) {
                        queryWrapper.in("shop_id", shopIds);
//                    }
                }


            }
        }
        Page<ShopTakeout> page = new Page<ShopTakeout>(pageNo, pageSize);
        IPage<ShopTakeout> pageList = shopTakeoutService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param shopTakeout
     * @return
     */
    @AutoLog(value = "店铺外卖信息-添加")
    @ApiOperation(value = "店铺外卖信息-添加", notes = "店铺外卖信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ShopTakeout shopTakeout) {
        if (oConvertUtils.isEmpty(shopTakeout.getShopId())) {
            return Result.error("参数错误");
        }
        //check 不能重复提交
        ShopTakeout checkMany = shopTakeoutService.getOne(new QueryWrapper<ShopTakeout>().eq("shop_id", shopTakeout.getShopId()));
        if (oConvertUtils.isNotEmpty(checkMany)) {
            return Result.error("该门店已有外卖信息,请勿重复提交~");
        }
        ShopBasic shopBasic = shopBasicService.getById(shopTakeout.getShopId());
        shopTakeout.setChannelId(shopBasic.getChannelId());
        shopTakeoutService.save(shopTakeout);
        // his
        ShopTakeoutHis his = new ShopTakeoutHis();
        BeanUtils.copyProperties(shopTakeout, his);
        his.setTackoutId(shopTakeout.getId());
        his.setId(null);
        shopTakeoutHisService.save(his);
        return Result.OK("添加成功！", true);
    }

    /**
     * 编辑
     *
     * @param shopTakeout
     * @return
     */
    @AutoLog(value = "店铺外卖信息-编辑")
    @ApiOperation(value = "店铺外卖信息-编辑", notes = "店铺外卖信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ShopTakeout shopTakeout) {

        if (oConvertUtils.isEmpty(shopTakeout.getShopId())) {
            return Result.error("参数错误");
        }
        // his
        ShopTakeoutHis his = new ShopTakeoutHis();
        his.setTackoutId(shopTakeout.getId());
        BeanUtils.copyProperties(shopTakeout, his);

        ShopBasic shopBasic = shopBasicService.getById(shopTakeout.getShopId());
        shopTakeout.setChannelId(shopBasic.getChannelId());
        shopTakeoutService.updateById(shopTakeout);
        his.setId(null);
        his.setUpdateBy(shopTakeout.getUpdateBy());
        his.setUpdateTime(shopTakeout.getUpdateTime());
        shopTakeoutHisService.save(his);
        return Result.OK("编辑成功!", true);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "店铺外卖信息-通过id删除")
    @ApiOperation(value = "店铺外卖信息-通过id删除", notes = "店铺外卖信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        shopTakeoutService.removeById(id);
        return Result.OK("删除成功!", true);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "店铺外卖信息-批量删除")
    @ApiOperation(value = "店铺外卖信息-批量删除", notes = "店铺外卖信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.shopTakeoutService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!", true);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "店铺外卖信息-通过id查询")
    @ApiOperation(value = "店铺外卖信息-通过id查询", notes = "店铺外卖信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ShopTakeout shopTakeout = shopTakeoutService.getById(id);
        if (shopTakeout == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(shopTakeout);
    }
    /**
     * 通过ShopId查询
     *
     * @param shopId
     * @return
     */
    @AutoLog(value = "店铺外卖信息-通过ShopId查询")
    @ApiOperation(value = "店铺外卖信息-通过ShopId查询", notes = "店铺外卖信息-通过ShopId查询")
    @GetMapping(value = "/queryByShopId")
    public Result<?> queryByShopId(@RequestParam(name = "shopId", required = true) String shopId) {
        ShopTakeout shopTakeout = shopTakeoutService.getOne(new QueryWrapper<ShopTakeout>().eq("shop_id",shopId).last(" limit 1"));
        if (shopTakeout == null) {
            return Result.error(HttpStatus.NOT_FOUND.value(), "未找到对应数据");
        }
        return Result.OK(shopTakeout);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param shopTakeout
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ShopTakeout shopTakeout) {
        return super.exportXls(request, shopTakeout, ShopTakeout.class, "店铺外卖信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ShopTakeout.class);
    }

}
